package com.sap.sap_mangers.service.Impl;

import com.sap.sap_mangers.Vo.SawbsVo.*;
import com.sap.sap_mangers.Vo.SawbsVo.ManagerToUserVo.ManagerAllVo;
import com.sap.sap_mangers.Vo.SawbsVo.ManagerToUserVo.ManagerOrderVo;
import com.sap.sap_mangers.Vo.SawbsVo.ManagerToUserVo.ManagerWeekVo;
import com.sap.sap_mangers.Vo.SawbsVo.ManagerToUserVo.ManagerYearVo;
import com.sap.sap_mangers.Vo.UserVo.UserMessage;
import com.sap.sap_mangers.dto.sawbs.SawbsMessage;
import com.sap.sap_mangers.dto.sawbs.SawbsSummaryDto;
import com.sap.sap_mangers.dto.sawbs.SawbsTaskSummary;
import com.sap.sap_mangers.dto.sawbs.TaskForWeek;
import com.sap.sap_mangers.email.IMailService;
import com.sap.sap_mangers.mapper.DynamicMapper;
import com.sap.sap_mangers.mapper.SawbsMapper;
import com.sap.sap_mangers.mapper.UserMapper;
import com.sap.sap_mangers.pojo.*;
import com.sap.sap_mangers.service.CacheService;
import com.sap.sap_mangers.service.SawbsService;
import com.sap.sap_mangers.until.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;

/**
 * @author 樊东升
 * @date 2022/7/31 19:23
 */
@Service
public class SawbsServiceImpl implements SawbsService {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    private final SawbsMapper sawbsMapper;
    private final DynamicMapper dynamicMapper;
    private final UserMapper userMapper;
    private final CosUntil cosUntil;
    private final CacheService cacheService;
    private final IMailService iMailService;

    @Autowired
    public SawbsServiceImpl(SawbsMapper sawbsMapper, DynamicMapper dynamicMapper, UserMapper userMapper, CosUntil cosUntil, CacheService cacheService, IMailService iMailService) {
        this.sawbsMapper = sawbsMapper;
        this.dynamicMapper = dynamicMapper;
        this.userMapper = userMapper;
        this.cosUntil = cosUntil;
        this.cacheService = cacheService;
        this.iMailService = iMailService;
    }

    @Override
    public List<SawbsMessageVo> getSawbsMessage(SawbsMessage sawbsMessage) {
        return sawbsMapper.getSawbsMessage(sawbsMessage);
    }

    @Override
    public SimpleJson applyToBeStudyGroupLeader() {
        String username = JwtUtil.getUserForToken();
        SapSawbsApproval approvalMessageByUsername = sawbsMapper.getApprovalMessageByUsername(username);
        if (approvalMessageByUsername != null) {
            return new SimpleJson(3, "当前活动已经申请过，请勿重新申请");
        }
        Activity activityMessage = sawbsMapper.getActivityMessage(Integer.valueOf(dynamicMapper.getYear()), Integer.valueOf(dynamicMapper.getOrder()));
        if (activityMessage == null) {
            return new SimpleJson(3, "当前无活动需要申请");
        }
        User userByUserName = userMapper.getUserByUserName(username);
        if (userByUserName.getRole() >= ConstantUntil.ROLE_ORDINARY_MEMBERS) {
            return new SimpleJson(2, "您的权限无法申请成为负责人");
        }
        activityMessage.setUsername(username);
        activityMessage.setSawbsApprovalCreatetime(new Timestamp(System.currentTimeMillis()));
        try {
            sawbsMapper.applyToBeStudyGroupLeader(activityMessage.getUsername(), activityMessage.getSawbsActivityTheme(), activityMessage.getSawbsActivityContext(), activityMessage.getSawbsApprovalCreatetime(), activityMessage.getSawbsActivityYear(), activityMessage.getSawbsActivityOrder());
        } catch (Exception e) {
            e.printStackTrace();
            return new SimpleJson(1, "申请失败，可能服务器出错！");
        }
        return new SimpleJson(0, "申请成功，请等待会长审批");
    }

    @Override
    public SimpleJson getApprovalMessage() {
        return new SimpleJson(0, "获取成功", sawbsMapper.getApprovalVo());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void responsibleForApproval(String username) {
        Timestamp nowDate = new Timestamp(System.currentTimeMillis());
        sawbsMapper.responsibleForApproval(username, JwtUtil.getUserForToken(), nowDate);
        sawbsMapper.addMangerByUsername(username);
    }

    @Override
    public void createActivity(Activity activity) {
        sawbsMapper.createActivity(activity);
        sawbsMapper.addActivityOrderForRecordTable(activity.getSawbsActivityYear(), activity.getSawbsActivityOrder());
    }

    @Override
    public SimpleJson getManagerUsers() {
        SapSawbsMangers sawbsManagerMessageByUsername = sawbsMapper.getSawbsManagerMessageByUsername(JwtUtil.getUserForToken());
        if (sawbsManagerMessageByUsername == null) {
            return new SimpleJson(1, "操作失败，您当前不是负责人");
        }
        if (sawbsManagerMessageByUsername.getSawbsMangersExist() == 1) {
            return new SimpleJson(3, "您已经申请退出当前活动，无法获取内容!");
        }
        List<DetailsUser> managerUsers = getDetailsUsers();
        if (managerUsers == null || managerUsers.size() == 0) {
            return new SimpleJson(2, "当前还未给您分配学习小组成员，请耐心等待!");
        }
        getMangerUserMessage(managerUsers);
        SawbsManagerToUser sawbsManagerToUser = new SawbsManagerToUser();
        sawbsManagerToUser.setUserDetails(managerUsers);
        List<SawbsMessageVo> userScore = new ArrayList<>();
        for (DetailsUser managerUser : managerUsers) {
            SawbsMessageVo sawbsMessageByUsername = sawbsMapper.getSawbsMessageByUsername(managerUser.getUserDetailsId().toString());
            userScore.add(sawbsMessageByUsername);
        }
        sawbsManagerToUser.setUserScore(userScore);
        System.out.println(sawbsManagerToUser);
        return new SimpleJson(0, "操作成功", sawbsManagerToUser);
    }

    /**
     * 获取负责人对应的被负责人的信息(存在已经评分的会被打上已评分的标志)
     *
     * @param managerUsers 负责人对应的负责表
     */
    private void getMangerUserMessage(List<DetailsUser> managerUsers) {
        SawbsMessageVo sawbsMessageVo = new SawbsMessageVo();
        String year = dynamicMapper.getYear();
        String order = dynamicMapper.getOrder();
        String week = dynamicMapper.getWeek();
        sawbsMessageVo.setYear(Integer.parseInt(year));
        sawbsMessageVo.setOrder(Integer.parseInt(order));
        sawbsMessageVo.setWeek(Integer.parseInt(week));
        for (DetailsUser managerUser : managerUsers) {
            System.out.println(managerUser);
            sawbsMessageVo.setUsername(managerUser.getUserDetailsId().toString());
            SawbsMessageVo weekScore = sawbsMapper.getWeekScore(sawbsMessageVo);
            System.out.println(weekScore);
            if (weekScore != null) {
                managerUser.setRealName(managerUser.getRealName() + "(已评分)");
            }
        }
    }

    /**
     * 从数据库拿到当前周数的负责人对应负责的内容
     *
     * @return List<DetailsUser>
     */
    private List<DetailsUser> getDetailsUsers() {
        DynamicMessage dynamicMessage = new DynamicMessage(dynamicMapper.getAllContext());
        return sawbsMapper.getManagerUsers(dynamicMessage, JwtUtil.getUserForToken());
    }

    @Override
    public List<ManagerCorrespondence> getAllManagerCorrespondenceDefaultByDynamicTable(DynamicMessage dynamicMessage) {
        dynamicMessage.setDefaultTimeByDynamicTable(new DynamicMessage(dynamicMapper.getAllContext()));
        return sawbsMapper.getAllMangerCorrespondenceDefaultByDynamicTable(dynamicMessage);
    }

    @Override
    public String getMangerId() {
        return sawbsMapper.getMangerId(JwtUtil.getUserForToken(), new DynamicMessage(dynamicMapper.getAllContext()));
    }

    @Override
    public SapSawbsMangers getSapSawbsMangers(String username) {
        return sawbsMapper.getSapSawbsMangers(username);
    }

    @Override
    public void memberExit() {
        sawbsMapper.memberExit(Integer.valueOf(dynamicMapper.getYear()), Integer.valueOf(dynamicMapper.getOrder()), JwtUtil.getUserForToken());
    }

    @Override
    public void managerExit() {
        //当前活动年份
        Integer year = Integer.valueOf(dynamicMapper.getYear());
        //当前活动次数
        Integer order = Integer.valueOf(dynamicMapper.getOrder());
        //申请退出的负责人的学号
        String username = JwtUtil.getUserForToken();
        //负责人退出
        sawbsMapper.managerExit(year, order, username);

        //退出后要将本周还没有进行评分的成员分配给会长
        //获取会长学号
        String presidentUserName = userMapper.getPresidentUserName();
        //查询该负责人原本在本周该负责的成员的学号
        List<String> userUsernameList = sawbsMapper.getSawbsUserUsername(username);
        //查询每个成员是否已经生成评分 (没有评分的将负责匹配关系转移给会长)
        for (String userUsername : userUsernameList) {
            //本周评分表中没有这个成员的记录
            if (sawbsMapper.getSawbsScoreIdThisWeek(userUsername) == null) {
                //负责匹配关系表中将其本周负责人修改成会长
                sawbsMapper.updateWeeklyManagerMatchingRelationship(presidentUserName, userUsername);
            }
        }
    }

    @Override
    public SimpleJson writeSawbsMessageVo(SawbsMessageVo sawbsMessageVo) {
        sawbsMessageVo.setDefaultTimeByDynamicTable(new DynamicMessage(dynamicMapper.getAllContext()));
        sawbsMessageVo.setManagerName(JwtUtil.getUserForToken());
        Long relationsCount = sawbsMapper.existResponsibilityRelations(sawbsMessageVo);
        if (relationsCount == null || relationsCount == 0) {
            return new SimpleJson(1, "操作失败，未找到您的成员", null);
        }
        sawbsMapper.writeSawbsMessageVo(sawbsMessageVo);
        sawbsMessageVo.setName(cacheService.getRealNameCache(cacheService.getRealNameCacheMap(), sawbsMessageVo.getUsername()));
        List<DetailsUser> detailsUsers = getDetailsUsers();
        getMangerUserMessage(detailsUsers);
        getDetailsUserForWeekScore(detailsUsers, sawbsMessageVo);
        String qq = userMapper.getQQByUsername(sawbsMessageVo.getUsername());
        iMailService.sendHtmlMail(qq+"@qq.com","学习评价",EmailUntil.sendEmailToCompleteEvaluation(
                sawbsMessageVo.getNote(),
                sawbsMessageVo.getDepth(),
                sawbsMessageVo.getEnthusiasm(),
                sawbsMessageVo.getSummary(),
                sawbsMessageVo.getComprehensive(),
                sawbsMessageVo.getDesc(),
                sawbsMessageVo.getName(),
                "你提交的周任务已评分"
        ));
        return new SimpleJson(0, "学习评价写入成功", sawbsMessageVo);
    }

    @Override
    public SimpleJson getWeekScore(SawbsMessageVo sawbsMessageVo) {
        sawbsMessageVo.setUsername(JwtUtil.getUserForToken());
        sawbsMessageVo.setDefaultTimeByDynamicTable(new DynamicMessage(dynamicMapper.getAllContext()));
        SawbsMessageVo weekScore = sawbsMapper.getWeekScore(sawbsMessageVo);
        if (weekScore == null) {
            return new SimpleJson(1, "获取失败，该时间没有对您的评分");
        }
        weekScore.setName(cacheService.getRealNameCache(cacheService.getRealNameCacheMap(), sawbsMessageVo.getUsername()));
        String mangerId = sawbsMapper.getMangerId(sawbsMessageVo.getUsername(), new DynamicMessage(weekScore.getYear(), weekScore.getOrder(), weekScore.getWeek()));
        weekScore.setManagerName(cacheService.getRealNameCache(cacheService.getRealNameCacheMap(), mangerId));
        return new SimpleJson(0, "获取成功", weekScore);
    }

    @Override
    public SimpleJson getUsersActivityMessageOfYear(Integer year) {
        if (year == null) {
            year = Integer.parseInt(dynamicMapper.getYear());
        }
        List<SawbsUser> usersActivityMessageOfYear = sawbsMapper.getUsersActivityMessageOfYear(year);
        if (usersActivityMessageOfYear == null || usersActivityMessageOfYear.size() == 0) {
            return new SimpleJson(1, "暂无" + year + "届成员活动信息");
        }
        return new SimpleJson(0, "获取成功", usersActivityMessageOfYear);
    }

    @Override
    public SapSawbsActivity getThisSawbsActivity() {
        return sawbsMapper.getThisSawbsActivity();
    }

    @Override
    public SapSawbsActivity getSawbsActivityByCondition(Integer year, Integer order) {
        return sawbsMapper.getSawbsActivityByCondition(year, order);
    }

    @Override
    public List<SapSawbsActivity> getAllSawbsActivities() {
        return sawbsMapper.getAllSawbsActivities();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SimpleJson addTaskForWeek(MultipartFile file, MultipartFile image, String theme, String context, String fileName, String imageName) {
        String fileUrl;
        String imageUrl;
        fileName = "[" + dynamicMapper.getOrder() + "-" + dynamicMapper.getWeek() + "]-" + theme + ".md";
        String fileCosUrl = "SapFile/task/" + dynamicMapper.getYear() + "/" + dynamicMapper.getOrder() + "/" + fileName;
        try {
            fileUrl = cosUntil.getCosUrl(file, fileCosUrl);
        } catch (IOException e) {
            return new SimpleJson(5, e.getMessage());
        }
        String imageCosUrl = "SapImage/task/" + dynamicMapper.getYear() + "/" + dynamicMapper.getOrder() + "/" + imageName;
        try {
            imageUrl = cosUntil.getCosUrl(image, imageCosUrl);
        } catch (IOException e) {
            return new SimpleJson(5, e.getMessage());
        }
        SapSawbsTask taskThisWeek = getTaskThisWeek();
        if (taskThisWeek != null) {
            TaskForWeek taskForWeek = new TaskForWeek(theme, context, fileUrl, imageUrl, JwtUtil.getUserForToken(), new Timestamp(System.currentTimeMillis()), (int) (taskThisWeek.getSawbsTaskReviseFrequency() + 1));
            //System.out.println(taskForWeek);
            sawbsMapper.updateSawbsTask(taskForWeek);
            String msg = "修改成功！最后一次修改人:" + JwtUtil.getUserForToken() + "(" + cacheService.getRealNameCache(cacheService.getRealNameCacheMap(), JwtUtil.getUserForToken()) + ")";
            return new SimpleJson(4, msg);
        } else {
            TaskForWeek taskForWeek = new TaskForWeek(theme, context, fileUrl, imageUrl, JwtUtil.getUserForToken(), new Timestamp(System.currentTimeMillis()));
            sawbsMapper.addTaskForWeek(taskForWeek);
            List<String> allContext = dynamicMapper.getAllContext();
            sawbsMapper.updateToAddOneWeekForRecordTable(Integer.parseInt(allContext.get(0)), Integer.parseInt(allContext.get(1)));
        }
        return SimpleJson.SUCCESS;
    }


    @Override
    public SimpleJson updateSawbsMessageVo(SawbsMessageVo sawbsMessageVo) {
        sawbsMessageVo.setManagerName(JwtUtil.getUserForToken());
        Long aLong = sawbsMapper.existResponsibilityRelations(sawbsMessageVo);
        if (aLong == null || aLong == 0) {
            //权限不足
            return new SimpleJson(3, "修改-权限不足");
        }
        if (sawbsMessageVo.identityInformation()) {
            return new SimpleJson(4, "修改-修改分数范围[1,5]");
        }
        sawbsMessageVo.setDefaultTimeByDynamicTable(new DynamicMessage(dynamicMapper.getAllContext()));
        sawbsMapper.updateSawbsMessageVo(sawbsMessageVo);
        List<DetailsUser> detailsUsers = getDetailsUsers();
        getMangerUserMessage(detailsUsers);
        SawbsMessageVo weekScore = sawbsMapper.getWeekScore(sawbsMessageVo);
        getDetailsUserForWeekScore(detailsUsers, weekScore);
        String qq = userMapper.getQQByUsername(sawbsMessageVo.getUsername());
        iMailService.sendHtmlMail(qq+"@qq.com","学习评价重新打分",EmailUntil.sendEmailToCompleteEvaluation(
                sawbsMessageVo.getNote(),
                sawbsMessageVo.getDepth(),
                sawbsMessageVo.getEnthusiasm(),
                sawbsMessageVo.getSummary(),
                sawbsMessageVo.getComprehensive(),
                sawbsMessageVo.getDesc(),
                sawbsMessageVo.getName(),
                "你提交的周任务已重新评分"
        ));
        return new SimpleJson(0, "修改-修改成功", weekScore);
    }

    /**
     * 获取周任务负责人对应被负责人的分数表
     *
     * @param detailsUsers 被负责人的详细信息
     * @param weekScore    分数
     */
    private void getDetailsUserForWeekScore(List<DetailsUser> detailsUsers, SawbsMessageVo weekScore) {
        weekScore.setManagerUsers(detailsUsers);
        List<SawbsMessageVo> scoreUserMessage = new ArrayList<>();
        for (DetailsUser detailsUser : detailsUsers) {
            SawbsMessageVo sawbsMessageByUsername = sawbsMapper.getSawbsMessageByUsername(String.valueOf(detailsUser.getUserDetailsId()));
            scoreUserMessage.add(sawbsMessageByUsername);
        }
        weekScore.setUserScore(scoreUserMessage);
    }

    @Override
    public boolean existUserScoreInSawbsScoreTable(SawbsMessageVo sawbsMessageVo) {
        sawbsMessageVo.setDefaultTimeByDynamicTable(new DynamicMessage(dynamicMapper.getAllContext()));
        SawbsMessageVo weekScore = sawbsMapper.getWeekScore(sawbsMessageVo);
        return weekScore != null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int createWeeklyManagerMatchingRelationship() {
        //获取当前活动的相关信息(动态表中的数据)
        Integer year = Integer.valueOf(dynamicMapper.getYear());
        Integer order = Integer.valueOf(dynamicMapper.getOrder());
        Integer week = Integer.valueOf(dynamicMapper.getWeek());
        DynamicMessage dynamicMessage = new DynamicMessage(year, order, week);
        //给新加入的学员(其他人之前本周已经分配过负责人了)分配负责人 (sql根据order获取)
        List<String> thisWeekNotAllocationManagerPeople = sawbsMapper.getThisWeekNotAllocationManagerPeople(dynamicMessage);
        if (!thisWeekNotAllocationManagerPeople.isEmpty()) {
            allocationPeopleToManager(year, order, week, thisWeekNotAllocationManagerPeople);
            return 2;
        }
        //如果有人提交过文件，不允许重新分配
        List<SapSawbsUserResults> thisWeekIsPeopleSubmitTask = sawbsMapper.getThisWeekIsPeopleSubmitTask(dynamicMessage);
        if (!thisWeekIsPeopleSubmitTask.isEmpty()) {
            return 1;
        }

        //判断是否生成过这周的数据，如果生成过，先将上次生成的数据删除
        if (!sawbsMapper.getManagerCorrespondenceId(year, order, week).isEmpty()) {
            //删除之前的数据
            sawbsMapper.deleteThisWeekManagerCorrespondence(year, order, week);
            //删除之前生成的成员周任务提交结果记录表数据
            sawbsMapper.deleteThisWeekUserSubmitResult(year, order, week);
        }
        //获取未退出的成员的学号
        List<String> usersThatHaveNotExited = sawbsMapper.getUsersThatHaveNotExited(year, order);
        //分配负责人
        allocationPeopleToManager(year, order, week, usersThatHaveNotExited);
        return 0;
    }

    /**
     * 分配学员给负责人
     *
     * @param year                   年
     * @param order                  活动次数
     * @param week                   周数
     * @param usersThatHaveNotExited 当前需要分配的人员
     */
    private void allocationPeopleToManager(Integer year, Integer order, Integer week, List<String> usersThatHaveNotExited) {
        //对成员随机排序
        Collections.shuffle(usersThatHaveNotExited, new Random(System.currentTimeMillis()));
        //获取未退出的负责人
        List<String> managersThatHaveNotExited = sawbsMapper.getManagersThatHaveNotExited(year, order);
        //对负责人随机排序
        Collections.shuffle(managersThatHaveNotExited, new Random(System.currentTimeMillis()));
        //成员人数
        int usersNumber = usersThatHaveNotExited.size();
        //负责人人数
        int managerNumber = managersThatHaveNotExited.size();
        //平均每位负责人至少需要负责的人数 (无法整除时多出的成员后面单独处理)
        int avgNumber = usersNumber / managerNumber;
        //int型除法多出的部分 剩余人数
        int remainingNumber = usersNumber - managerNumber * avgNumber;

        //redis缓存-真实姓名
        Map<String, String> realNameCacheMap = cacheService.getRealNameCacheMap();
        //成员集合的索引
        int idx = 0;
        //将已经随机处理的成员分别依据‘avgNumber’的值分配给负责人(一个负责人至少分配‘avgNumber’个成员)
        //同时还要处理因int除法而缺失的人数
        //显然剩余人数<负责人个数，而且前面对负责人列表已经进行随机排序(对负责人列表随机排序避免了总是重复的负责人多分配一个成员)
        //所以给随机排序后的负责人列表的前remainingNumber个均多分配一个即可对剩余人数随机排序(有‘remainingNumber’个负责人要多分配一个)
        for (String managerId : managersThatHaveNotExited) {
            //每个负责人至少负责‘avgNumber’个成员
            int number = avgNumber;
            //有‘remainingNumber’个负责人要多分配一个成员
            if (remainingNumber > 0) {
                ++number;
                --remainingNumber;
            }
            for (int i = 0; i < number; ++i) {
                //生成和添加负责关系
                String userUsername = usersThatHaveNotExited.get(idx);
                ManagerCorrespondence managerCorrespondence = new ManagerCorrespondence(null, managerId, userUsername, year, order, week, null, null);
                sawbsMapper.addManagerCorrespondence(managerCorrespondence);
                //添加成员周任务提交表初始数据
                String userQq = userMapper.getUserByUserName(userUsername).getQq();
                SapSawbsUserResults sapSawbsUserResults = new SapSawbsUserResults(null, userUsername, cacheService.getRealNameCache(realNameCacheMap, userUsername), userQq, year, order, week, managerId, cacheService.getRealNameCache(realNameCacheMap, managerId), null, null, 0, null);
                sawbsMapper.addUserSubmitResult(sapSawbsUserResults);
                ++idx;
            }
        }
    }


    @Override
    public SapSawbsTask getTaskThisWeek() {
        SapSawbsTask taskThisWeek = sawbsMapper.getTaskThisWeek();
        if (taskThisWeek == null) {
            return null;
        } else {
            if (!Objects.equals(taskThisWeek.getSawbsTaskReviseUser(), "无")) {
                taskThisWeek.setSawbsTaskReviseUser(userMapper.getUserMessage(taskThisWeek.getSawbsTaskReviseUser()).getRealName());
                taskThisWeek.setSawbsTaskUser(userMapper.getUserMessage(taskThisWeek.getSawbsTaskUser()).getRealName());
            } else {
                taskThisWeek.setSawbsTaskUser(userMapper.getUserMessage(taskThisWeek.getSawbsTaskUser()).getRealName());
            }
        }
        return taskThisWeek;
    }

    @Override
    public List<SapSawbsTask> getTaskThisOrder() {
        return sawbsMapper.getTaskThisOrder();
    }

    @Override
    public List<SapSawbsTask> getTaskByCondition(Integer year, Integer order) {
        return sawbsMapper.getTaskByCondition(year, order);
    }

    /**
     * 通过数据来筛选到底是调用按个接口
     *
     * @param year        年份
     * @param order       活动次数
     * @param week        周数
     * @param ignoreOrder 是否为年总结
     * @param ignoreWeek  是否为活动总结
     * @return 视图
     */
    private SimpleJson getSummaryMessage(Integer year, Integer order, Integer week, Integer ignoreOrder, Integer ignoreWeek) {
        try {
            SawbsSummaryDto sawbsSummaryDto = new SawbsSummaryDto(year, order, week, ignoreOrder, ignoreWeek);
            List<SapSawbsTaskSummaryImage> taskSummaryImageUrl = sawbsMapper.getTaskSummaryImageUrl();
            List<String> summaryUrlList = new ArrayList<>();
            List<SapSawbsTaskSummary> summaryMessage = null;
            if (year == null) {
                int yearDynamic = Integer.parseInt(dynamicMapper.getYear());
                int orderDynamic = Integer.parseInt(dynamicMapper.getOrder());
                int weekDynamic = Integer.parseInt(dynamicMapper.getWeek());
                if (weekDynamic != 1) {
                    weekDynamic = weekDynamic - 1;
                }
                sawbsSummaryDto.setYear(yearDynamic);
                sawbsSummaryDto.setOrder(orderDynamic);
                sawbsSummaryDto.setWeek(weekDynamic);
                sawbsSummaryDto.setIgnoreOrder(ignoreOrder);
                sawbsSummaryDto.setIgnoreWeek(ignoreWeek);
                summaryMessage = sawbsMapper.getSummaryMessage(sawbsSummaryDto);
                if (summaryMessage.isEmpty()) {
                    return new SimpleJson(1, "最新的活动还没有上传周总结，或者上周没有上传总结！");
                }
                SapSawbsTaskSummary sapSawbsTaskSummary = summaryMessage.get(0);
                for (SapSawbsTaskSummaryImage sapSawbsTaskSummaryImage : taskSummaryImageUrl) {
                    if (Long.parseLong(sapSawbsTaskSummary.getSawbsTaskSummaryImageId()) == sapSawbsTaskSummaryImage.getSawbsTaskSummaryImageId()) {
                        summaryUrlList.add(sapSawbsTaskSummaryImage.getSawbsTaskSummaryImageUrl());
                    }
                }
                sapSawbsTaskSummary.setOrderName(sawbsMapper.getOrderName(new DynamicMessage(yearDynamic, orderDynamic, null)));
                sapSawbsTaskSummary.setImageUrl(summaryUrlList);
            } else if (order == null) {
                summaryMessage = getSummaryMessage(year, order, week, ignoreOrder, ignoreWeek, sawbsSummaryDto, taskSummaryImageUrl);
            } else if (week == null) {
                summaryMessage = getSummaryMessage(year, order, week, ignoreOrder, ignoreWeek, sawbsSummaryDto, taskSummaryImageUrl);
            } else if (ignoreOrder == 0 && ignoreWeek == 0) {
                summaryMessage = getSummaryMessage(year, order, week, ignoreOrder, ignoreWeek, sawbsSummaryDto, taskSummaryImageUrl);
            } else {
                if (ignoreOrder == 1 && ignoreWeek == 0) {
                    summaryMessage = getSummaryMessage(year, order, week, ignoreOrder, ignoreWeek, sawbsSummaryDto, taskSummaryImageUrl);
                } else if (ignoreOrder == 1 && ignoreWeek == 1) {
                    summaryMessage = getSummaryMessage(year, order, week, ignoreOrder, ignoreWeek, sawbsSummaryDto, taskSummaryImageUrl);
                }
            }
            assert summaryMessage != null;
            if (summaryMessage.isEmpty()) {
                return new SimpleJson(0, "获取成功", null);
            }
            if (year != null && order != null) {
                for (SapSawbsTaskSummary sapSawbsTaskSummary : summaryMessage) {
                    sapSawbsTaskSummary.setOrderName(sawbsMapper.getOrderName(new DynamicMessage(year, order, null)));
                }
            }
            return new SimpleJson(0, "获取成功", summaryMessage);
        } catch (Exception e) {
            e.printStackTrace();
            return new SimpleJson(1, "运行出错");
        }
    }

    /**
     * 获取总结表的信息
     *
     * @param year                年份
     * @param order               活动次数
     * @param week                周数
     * @param ignoreOrder         是否是年总结
     * @param ignoreWeek          是否为活动总结
     * @param sawbsSummaryDto     总结表所需要的数据
     * @param taskSummaryImageUrl 图片表
     * @return List<SapSawbsTaskSummary>
     */
    private List<SapSawbsTaskSummary> getSummaryMessage(Integer year, Integer order, Integer week, Integer ignoreOrder, Integer ignoreWeek, SawbsSummaryDto sawbsSummaryDto, List<SapSawbsTaskSummaryImage> taskSummaryImageUrl) {
        List<SapSawbsTaskSummary> summaryMessage;
        sawbsSummaryDto.setYear(year);
        sawbsSummaryDto.setOrder(order);
        sawbsSummaryDto.setWeek(week);
        sawbsSummaryDto.setIgnoreOrder(ignoreOrder);
        sawbsSummaryDto.setIgnoreWeek(ignoreWeek);
        summaryMessage = getSapSawbsTaskSummaries(sawbsSummaryDto, taskSummaryImageUrl);
        return summaryMessage;
    }

    /**
     * 首先是通过年份，活动次序，还有周数，是否是年总结，是否是活动总结来把数据库的数据加载到内存里
     * 然后我们在通过if判断来筛选我们需要的数据，依据是总结表和总结图片表里对应的ID
     *
     * @param sawbsSummaryDto     年，活动，周数据
     * @param taskSummaryImageUrl 图片表
     * @return List<SapSawbsTaskSummary> 总结表list
     */
    private List<SapSawbsTaskSummary> getSapSawbsTaskSummaries(SawbsSummaryDto sawbsSummaryDto, List<SapSawbsTaskSummaryImage> taskSummaryImageUrl) {
        List<SapSawbsTaskSummary> summaryMessage;
        summaryMessage = sawbsMapper.getSummaryMessage(sawbsSummaryDto);
        for (SapSawbsTaskSummary sapSawbsTaskSummary : summaryMessage) {
            List<String> summaryUrlList = new ArrayList<>();
            for (SapSawbsTaskSummaryImage sapSawbsTaskSummaryImage : taskSummaryImageUrl) {
                if (Long.parseLong(sapSawbsTaskSummary.getSawbsTaskSummaryImageId()) == sapSawbsTaskSummaryImage.getSawbsTaskSummaryImageId()) {
                    summaryUrlList.add(sapSawbsTaskSummaryImage.getSawbsTaskSummaryImageUrl());
                }
            }
            sapSawbsTaskSummary.setImageUrl(summaryUrlList);
        }
        return summaryMessage;
    }

    @Override
    public SimpleJson getSummaryMessageByYear(String year) {
        return getSummaryMessage(Integer.valueOf(year), null, null, 0, 0);

    }

    @Override
    public SimpleJson getSummaryMessageByOrder(String year, String order) {
        return getSummaryMessage(Integer.valueOf(year), Integer.valueOf(order), null, 0, 0);

    }

    @Override
    public SimpleJson getSummaryMessageByWeek(String year, String order, String week) {
        return getSummaryMessage(Integer.valueOf(year), Integer.valueOf(order), Integer.valueOf(week), 0, 0);
    }

    @Override
    public SimpleJson getSummaryMessageOfYear(String year) {
        return getSummaryMessage(Integer.valueOf(year), null, null, 1, 0);
    }

    @Override
    public SimpleJson getSummaryMessageOfOrder(String year, String order) {
        return getSummaryMessage(Integer.valueOf(year), Integer.valueOf(order), null, 0, 1);
    }

    @Override
    public SimpleJson getSummaryMessageByDynamic() {
        return getSummaryMessage(null, null, null, 0, 0);
    }

    @Override
    public SimpleJson addSummaryMessage(SawbsTaskSummary sawbsTaskSummary, List<String> imageUrlList) {
        try {
            sawbsMapper.addTaskSummaryMessage(sawbsTaskSummary);
            for (String url : imageUrlList) {
                SawbsSummaryDto sawbsSummaryDto = new SawbsSummaryDto(sawbsTaskSummary.getImageId(), sawbsTaskSummary.getYear(), sawbsTaskSummary.getOrder(), sawbsTaskSummary.getWeek(), sawbsTaskSummary.getIgnoreOrder(), sawbsTaskSummary.getIgnoreWeek(), url);
                sawbsMapper.addTaskSummaryImage(sawbsSummaryDto);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return SimpleJson.FAILURE;
        }
        return new SimpleJson(0, "总结添加成功", getSummaryMessageByDynamic().getData());
    }

    @Override
    public SimpleJson updateTaskSummaryMessage(SawbsTaskSummary sawbsTaskSummary, List<String> imageUrlList) {
        try {
            sawbsMapper.updateTaskSummaryMessage(sawbsTaskSummary);
            for (String url : imageUrlList) {
                SawbsSummaryDto sawbsSummaryDto = new SawbsSummaryDto(sawbsTaskSummary.getImageId(), sawbsTaskSummary.getYear(), sawbsTaskSummary.getOrder(), sawbsTaskSummary.getWeek(), sawbsTaskSummary.getIgnoreOrder(), sawbsTaskSummary.getIgnoreWeek(), url);
                sawbsMapper.updateTaskSummaryImage(sawbsSummaryDto);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return SimpleJson.FAILURE;
        }
        return new SimpleJson(0, "总结修改成功", getSummaryMessageByDynamic().getData());
    }

    /**
     * 用于选软用户端首页的前12名最近一次分数情况
     *
     * @param order 活动次序
     * @return
     */
    @Override
    public SimpleJson getScoreForView(Integer order) {
        List<SawbsMessageVo> sawbsMessageSum = getSumPeopleScore(order);
        Collections.sort(sawbsMessageSum);
        if (sawbsMessageSum.size() > 12) {
            return new SimpleJson(sawbsMessageSum.subList(0, 12));
        } else {
            return new SimpleJson(sawbsMessageSum);
        }
    }

    /**
     * 获取所有成员一次活动的总分以及其他各项总分
     *
     * @param order 活动次数
     * @return
     */
    private List<SawbsMessageVo> getSumPeopleScore(Integer order) {
        List<SawbsMessageVo> sawbsMessageSum = null;
        if (order == -1) {
            sawbsMessageSum = sawbsMapper.getSawbsMessageSum(new SawbsMessage(Integer.valueOf(dynamicMapper.getViewYear()), Integer.valueOf(dynamicMapper.getViewOrder())));
        } else {
            sawbsMessageSum = sawbsMapper.getSawbsMessageSum(new SawbsMessage(Integer.valueOf(dynamicMapper.getYear()), order));
        }
        for (SawbsMessageVo sawbsMessageVo : Objects.requireNonNull(sawbsMessageSum)) {
            sawbsMessageVo.setSumScore(sawbsMessageVo.getNote() + sawbsMessageVo.getSummary() + sawbsMessageVo.getDepth() + sawbsMessageVo.getEnthusiasm() + sawbsMessageVo.getComprehensive());
        }
        Collections.sort(sawbsMessageSum);
        int rank = 1;
        for (SawbsMessageVo sawbsMessageVo : sawbsMessageSum) {
            sawbsMessageVo.setRank(rank);
            rank++;
            sawbsMessageVo.setSumPeople(sawbsMessageSum.size());
        }
        return sawbsMessageSum;
    }

    @Override
    public List<SapSawbsScore> getScoreForWeek(DynamicMessage dynamicMessage) {
        List<SapSawbsScore> scoreForWeek = sawbsMapper.getScoreForWeek(dynamicMessage);
        List<SapSawbsScore> result = new ArrayList<>(scoreForWeek.size());
        Collections.sort(scoreForWeek);
        for (SapSawbsScore sapSawbsScore : scoreForWeek) {
            SapSawbsScore sapSawbsScoresAndRank = getSapSawbsScoresAndRank(sapSawbsScore.getSawbsScoreUsername(), scoreForWeek, true);
            result.add(sapSawbsScoresAndRank);
        }
        Collections.sort(scoreForWeek);
        return result;
    }

    @Override
    public List<SawbsMessageVo> getScoreForOrder(Integer order) {
        return getSumPeopleScore(order);
    }

    @Override
    public List<SapSawbsScore> getScoreForAnyYear(Integer year) {
        List<SapSawbsScore> scoreForAnyYear;
        if (year == -1) {
            scoreForAnyYear = sawbsMapper.getScoreForAnyYear(Integer.valueOf(dynamicMapper.getYear()));
        } else {
            scoreForAnyYear = sawbsMapper.getScoreForAnyYear(year);
        }
        for (SapSawbsScore sapSawbsScore : Objects.requireNonNull(scoreForAnyYear)) {
            sapSawbsScore.setSumOfSawbsScore(sapSawbsScore.getSawbsScoreNote() + sapSawbsScore.getSawbsScoreSummary() + sapSawbsScore.getSawbsScoreDepth() + sapSawbsScore.getSawbsScoreEnthusiasm() + sapSawbsScore.getSawbsScoreComprehensive());
        }
        System.out.println(scoreForAnyYear);
        Collections.sort(scoreForAnyYear);
        int rank = 1;
        for (SapSawbsScore sapSawbsScore : scoreForAnyYear) {
            sapSawbsScore.setRank(rank);
            rank++;
            sapSawbsScore.setSumPeople(scoreForAnyYear.size());
        }
        System.out.println(scoreForAnyYear);
        return scoreForAnyYear;
    }

    @Override
    public SapSawbsScore getScoreForUser(DynamicMessage dynamicMessage) {
        List<SapSawbsScore> scoreForUser = sawbsMapper.getScoreForUser(dynamicMessage);
        return getSapSawbsScoresAndRank(dynamicMessage.getUsername(), scoreForUser, false);
    }

    @Override
    public List<SapSawbsScore> getScoreForUserOrder(DynamicMessage dynamicMessage) {
        List<SapSawbsScore> scoreForUser = sawbsMapper.getScoreForUser(dynamicMessage);
        Integer maxRecordWeekForOneOrder = sawbsMapper.getMaxRecordWeekForOneOrder(dynamicMessage.getYear(), dynamicMessage.getOrder());
        List<SapSawbsScore> list = new ArrayList<>();
        for (int i = 1; i <= maxRecordWeekForOneOrder; i++) {
            List<SapSawbsScore> sawbsScores = new ArrayList<>();
            for (SapSawbsScore sapSawbsScore : scoreForUser) {
                if (sapSawbsScore.getSawbsScoreWeeks() == i) {
                    sawbsScores.add(sapSawbsScore);
                }
            }
            SapSawbsScore sapSawbsScoresAndRank = getSapSawbsScoresAndRank(dynamicMessage.getUsername(), sawbsScores, false);
            list.add(sapSawbsScoresAndRank);
        }
        return list;
    }

    @Override
    public List<SapSawbsScore> getScoreForUserYear(DynamicMessage dynamicMessage) {
        List<Integer> allRecordOrderForOneYear = sawbsMapper.getAllRecordOrderForOneYear(dynamicMessage.getYear());
        List<SapSawbsScore> result = new ArrayList<>();
        for (Integer integer : allRecordOrderForOneYear) {
            dynamicMessage.setOrder(integer);
            List<SapSawbsScore> scoreForUserOrder = getScoreForUserOrder(dynamicMessage);
            result.addAll(scoreForUserOrder);
        }
        return result;
    }

    /**
     * 这里的有个小算法，主要是求分数排名，本身分数排名很简单，但是当分数相同的时候排名稍微难以处理
     * TreeMap储存的是从小到大，但是我们需要的分数是从大到小，所以需要转成list才能倒序遍历(2022年9月9日我不会，不知道以后会不会)
     *
     * @param username     学号
     * @param scoreForUser SapSawbsScore数组
     * @param isSort       是否是排序过后的，个人接口不需要传入排序的，但是分组接口需要传入排序的，不然对象地址会有问题
     * @return 数组信息携带等级
     */
    private SapSawbsScore getSapSawbsScoresAndRank(String username, List<SapSawbsScore> scoreForUser, Boolean isSort) {
        for (SapSawbsScore sapSawbsScore : scoreForUser) {
            sapSawbsScore.setSumOfSawbsScore(sapSawbsScore.getSawbsScoreNote() + sapSawbsScore.getSawbsScoreSummary() + sapSawbsScore.getSawbsScoreDepth() + sapSawbsScore.getSawbsScoreEnthusiasm() + sapSawbsScore.getSawbsScoreComprehensive());
        }
        if (!isSort) {
            Collections.sort(scoreForUser);
        }
        Map<Integer, Integer> treeMap = new TreeMap<>();
        for (SapSawbsScore sapSawbsScore : scoreForUser) {
            Integer key = (int) sapSawbsScore.getSumOfSawbsScore();
            if (treeMap.containsKey(key)) {
                Integer value = treeMap.get(key);
                treeMap.put(key, value + 1);
            } else {
                treeMap.put(key, 1);
            }
        }
        SapSawbsScore score = new SapSawbsScore();
        for (SapSawbsScore sapSawbsScore : scoreForUser) {
            if (Objects.equals(sapSawbsScore.getSawbsScoreUsername(), username)) {
                int rank = 0;
                Set<Map.Entry<Integer, Integer>> entries = treeMap.entrySet();
                List<Map.Entry<Integer, Integer>> entriesList = new ArrayList<>(entries);
                for (int i = entriesList.size() - 1; i >= 0; i--) {
                    if (entriesList.get(i).getKey() == sapSawbsScore.getSumOfSawbsScore()) {
                        rank++;
                        break;
                    }
                    rank++;
                }
                sapSawbsScore.setRank(rank);
                score = sapSawbsScore;
                score.setName(cacheService.getRealNameCache(cacheService.getRealNameCacheMap(), username));
                score.setSumPeople(scoreForUser.size());
            }
        }
        return score;
    }

    @Override
    public SapSawbsScore getScoreSumForUser(Integer year, Integer order, String username) {
        List<SapSawbsScore> scoreSumForUser = sawbsMapper.getScoreSumForUser(year, order, username);
        SapSawbsScore sapSawbsScoresAndRank = getSapSawbsScoresAndRank(username, scoreSumForUser, false);
        sapSawbsScoresAndRank.setSawbsScoreYear(year);
        sapSawbsScoresAndRank.setSawbsScoreOrder(order);
        return sapSawbsScoresAndRank;
    }

    @Override
    public SapSawbsScore getScoreSumForUserYear(Integer year, String username) {
        List<SapSawbsScore> sumYearAndScoreForUser = getSumYearAndScoreForUser(year, username);
        SapSawbsScore newSumScore = new SapSawbsScore();
        newSumScore.setSawbsScoreNote(0);
        newSumScore.setSawbsScoreSummary(0);
        newSumScore.setSawbsScoreDepth(0);
        newSumScore.setSawbsScoreEnthusiasm(0);
        newSumScore.setSawbsScoreComprehensive(0);
        newSumScore.setSumOfSawbsScore(0);
        int maxPeople = -1;
        for (SapSawbsScore sapSawbsScore : sumYearAndScoreForUser) {
            newSumScore.setSawbsScoreNote(newSumScore.getSawbsScoreNote() + sapSawbsScore.getSawbsScoreNote());
            newSumScore.setSawbsScoreSummary(newSumScore.getSawbsScoreSummary() + sapSawbsScore.getSawbsScoreSummary());
            newSumScore.setSawbsScoreDepth(newSumScore.getSawbsScoreDepth() + sapSawbsScore.getSawbsScoreDepth());
            newSumScore.setSawbsScoreEnthusiasm(newSumScore.getSawbsScoreEnthusiasm() + sapSawbsScore.getSawbsScoreEnthusiasm());
            newSumScore.setSawbsScoreComprehensive(newSumScore.getSawbsScoreComprehensive() + sapSawbsScore.getSawbsScoreComprehensive());
            newSumScore.setSumOfSawbsScore(newSumScore.getSumOfSawbsScore() + sapSawbsScore.getSumOfSawbsScore());
            if (sapSawbsScore.getSumPeople() > maxPeople) {
                maxPeople = sapSawbsScore.getSumPeople();
            }
        }
        newSumScore.setSumPeople(maxPeople);
        newSumScore.setSawbsScoreUsername(username);
        newSumScore.setName(cacheService.getRealNameCache(cacheService.getRealNameCacheMap(), username));
        return newSumScore;
    }

    @Override
    public List<SapSawbsScore> getSumYearAndScoreForUser(Integer year, String username) {
        List<Integer> allRecordOrderForOneYear = sawbsMapper.getAllRecordOrderForOneYear(year);
        List<SapSawbsScore> result = new ArrayList<>();
        for (Integer order : allRecordOrderForOneYear) {
            SapSawbsScore scoreSumForUser = getScoreSumForUser(year, order, username);
            result.add(scoreSumForUser);
        }
        return result;
    }

    @Override
    public SimpleJson getUserManagerForWeek(DynamicMessage dynamicMessage) {
        UserToManagerVo userManagerForWeek = sawbsMapper.getUserManagerForWeek(dynamicMessage);
        if (userManagerForWeek == null) {
            return new SimpleJson(1, "无法获取用户的负责人");
        }
        Activity activityMessage = sawbsMapper.getActivityMessage(dynamicMessage.getYear(), dynamicMessage.getOrder());
        String title = dynamicMessage.getYear()
                + "学年第" + dynamicMessage.getOrder()
                + "次活动(" + activityMessage.getSawbsActivityName()
                + ")";
        title += "第" + dynamicMessage.getWeek() + "周负责人";
        userManagerForWeek.setTitle(title);
        return new SimpleJson(userManagerForWeek);
    }

    @Override
    public ManagerForOrderVo getUserManagerForOrder(DynamicMessage dynamicMessage) {
        ManagerForOrderVo managerForOrderVo = new ManagerForOrderVo();
        try {
            List<SapSawbsManger> sapSawbsMangers = sawbsMapper.getSapSawbsManger(dynamicMessage.getYear(), dynamicMessage.getOrder(), dynamicMessage.getUsername());
            Activity activityMessage = sawbsMapper.getActivityMessage(dynamicMessage.getYear(), dynamicMessage.getOrder());
            if (!sapSawbsMangers.isEmpty()) {
                String title = sapSawbsMangers.get(0).getSawbsMangerYear()
                        + "学年第" + sapSawbsMangers.get(0).getSawbsMangerOrder()
                        + "次活动(" + activityMessage.getSawbsActivityName()
                        + ")";
                List<UserToManagerVo> list = new ArrayList<>();
                Collections.sort(sapSawbsMangers);
                for (SapSawbsManger sapSawbsManger : sapSawbsMangers) {
                    dynamicMessage.setWeek(Math.toIntExact(sapSawbsManger.getSawbsMangerWeek()));
                    UserToManagerVo userManagerForWeek = sawbsMapper.getUserManagerForWeek(dynamicMessage);
                    System.out.println(dynamicMessage);
                    userManagerForWeek.setTitle(title + "第" + sapSawbsManger.getSawbsMangerWeek() + "周负责人");
                    list.add(userManagerForWeek);
                }
                managerForOrderVo.setTitle(title);
                managerForOrderVo.setPeople(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return managerForOrderVo;
    }

    @Override
    public ManagerForYearVo


    getUserManagerForYear(DynamicMessage dynamicMessage) {

        List<SapSawbsManger> sapSawbsMangers = sawbsMapper.getSapSawbsManger(dynamicMessage.getYear(), null, dynamicMessage.getUsername());
        Set<Integer> set = new HashSet<>();
        for (SapSawbsManger sapSawbsManger : sapSawbsMangers) {
            set.add(sapSawbsManger.getSawbsMangerOrder());
        }
        List<ManagerForOrderVo> list = new ArrayList<>();
        ManagerForYearVo managerForYearVo = new ManagerForYearVo();
        List<Integer> sortSet = new ArrayList<>(set);
        for (Integer order : sortSet) {
            Activity activityMessage = sawbsMapper.getActivityMessage(dynamicMessage.getYear(), order);
            managerForYearVo.setTitle(dynamicMessage.getYear() + "学年第" + order + "次活动(" + activityMessage.getSawbsActivityName() + ")");
            ManagerForOrderVo userManagerForOrder = getUserManagerForOrder(new DynamicMessage(dynamicMessage.getYear(), order, null, dynamicMessage.getUsername()));
            list.add(userManagerForOrder);
        }
        managerForYearVo.setOrders(list);
        return managerForYearVo;
    }


    @Override
    public SapSawbsScore getSapSawbsScoreByUserLastOrder(String username) {
        return sawbsMapper.getSapSawbsScoreByUserLastOrder(username);
    }

    @Override
    public SimpleJson getSawbsActivityRecordOfYearOrderWeek(Integer year, Integer order) {
        //校验
        if (year == null && order != null) {
            return new SimpleJson(1, "暂无目标信息");
        }

        if (year == null) {
            List<Integer> allRecordYear = sawbsMapper.getAllRecordYear();
            if (allRecordYear != null && allRecordYear.size() != 0) {
                return new SimpleJson(0, "获取成功", sawbsMapper.getAllRecordYear());
            } else {
                return new SimpleJson(1, "暂无目标信息");
            }
        }
        if (order == null) {
            List<Integer> allRecordOrderForOneYear = sawbsMapper.getAllRecordOrderForOneYear(year);
            if (allRecordOrderForOneYear != null && allRecordOrderForOneYear.size() != 0) {
                return new SimpleJson(0, "获取成功", allRecordOrderForOneYear);
            } else {
                return new SimpleJson(1, "暂无目标信息");
            }
        }
        Integer aLlRecordWeekForOneOrder = sawbsMapper.getMaxRecordWeekForOneOrder(year, order);
        if (aLlRecordWeekForOneOrder != null) {
            return new SimpleJson(0, "获取成功", aLlRecordWeekForOneOrder);
        }
        return new SimpleJson(1, "暂无目标信息");
    }

    @Override
    public void addActivityOrderForRecordTable(Integer year, Integer order) {
        sawbsMapper.addActivityOrderForRecordTable(year, order);
    }

    @Override
    public ManagerVo getUserForManager() {
        DynamicMessage dynamicMessage = new DynamicMessage();
        dynamicMessage.setUsername("20212676");
        List<SapSawbsManger> sapSawbsMangers = sawbsMapper.getSapSawbsManger(null, null, dynamicMessage.getUsername());
        Set<Integer> set = new HashSet<>();
        for (SapSawbsManger sapSawbsManger : sapSawbsMangers) {
            set.add(sapSawbsManger.getSawbsMangerYear());
        }
        List<Integer> sortSet = new ArrayList<>(set);
        List<ManagerForYearVo> list = new ArrayList<>();
        ManagerVo managerVo = new ManagerVo();
        for (Integer year : sortSet) {
            dynamicMessage.setYear(year);
            ManagerForYearVo userManagerForYear = getUserManagerForYear(dynamicMessage);
            list.add(userManagerForYear);
        }
        for (Integer year : sortSet) {
            dynamicMessage.setYear(year);
            ManagerForYearVo userManagerForYear = getUserManagerForYear(dynamicMessage);
            list.add(userManagerForYear);
        }
        managerVo.setYear(list);
        return managerVo;
    }


    @Override
    public SimpleJson getManagerForUserWeek(DynamicMessage dynamicMessage) {
        ManagerWeekVo managerWeekVo = new ManagerWeekVo();
        try {
            Activity activityMessage = sawbsMapper.getActivityMessage(dynamicMessage.getYear(), dynamicMessage.getOrder());
            List<com.sap.sap_mangers.Vo.SawbsVo.ManagerToUserVo.ManagerVo> managerForUserWeek = sawbsMapper.getManagerForUserWeek(dynamicMessage);
            for (com.sap.sap_mangers.Vo.SawbsVo.ManagerToUserVo.ManagerVo managerVo : managerForUserWeek) {
                managerVo.setQq(userMapper.getQQByUsername(managerVo.getUsername()));
            }
            managerWeekVo.setUser(managerForUserWeek);
            managerWeekVo.setTitle(dynamicMessage.getYear() + "学年第" + dynamicMessage.getOrder() + "次活动(" + activityMessage.getSawbsActivityName() + ")" + "第" + dynamicMessage.getWeek() + "周");
        } catch (Exception e) {
            return new SimpleJson(1, "无信息");
        }
        return new SimpleJson(managerWeekVo);
    }

    @Override
    public SimpleJson getManagerForUserOrder(DynamicMessage dynamicMessage) {
        ManagerOrderVo managerOrderVo = new ManagerOrderVo();
        try {
            Integer maxRecordWeekForOneOrder = sawbsMapper.getMaxRecordWeekForOneOrder(dynamicMessage.getYear(), dynamicMessage.getOrder());

            List<ManagerWeekVo> list = new ArrayList<>();
            for (int i = 1; i <= maxRecordWeekForOneOrder; i++) {
                dynamicMessage.setWeek(i);
                SimpleJson managerForUserWeek = getManagerForUserWeek(dynamicMessage);
                list.add((ManagerWeekVo) managerForUserWeek.getData());
            }
            managerOrderVo.setWeeks(list);
            Activity activityMessage = sawbsMapper.getActivityMessage(dynamicMessage.getYear(), dynamicMessage.getOrder());
            managerOrderVo.setTitle(dynamicMessage.getYear() + "学年第" + dynamicMessage.getOrder() + "次活动(" + activityMessage.getSawbsActivityName() + ")");

        } catch (Exception e) {
            e.printStackTrace();
            return new SimpleJson(1, "无信息");
        }
        return new SimpleJson(managerOrderVo);
    }

    @Override
    public SimpleJson getManagerForUserYear(DynamicMessage dynamicMessage) {
        ManagerYearVo managerYearVo = new ManagerYearVo();
        try {
            List<Integer> allRecordOrderForOneYear = sawbsMapper.getAllRecordOrderForOneYear(dynamicMessage.getYear());
            List<ManagerOrderVo> list = new ArrayList<>();
            for (int i = 1; i <= allRecordOrderForOneYear.size(); i++) {
                dynamicMessage.setOrder(i);
                SimpleJson managerForUserOrder = getManagerForUserOrder(dynamicMessage);
                list.add((ManagerOrderVo) managerForUserOrder.getData());
            }
            managerYearVo.setOrders(list);
            managerYearVo.setTitle(dynamicMessage.getYear() + "学年");
        } catch (Exception e) {
            e.printStackTrace();
            return new SimpleJson(1, "无信息");
        }
        return new SimpleJson(managerYearVo);
    }

    @Override
    public SimpleJson getManagerForUser() {
        ManagerAllVo managerAllVo = new ManagerAllVo();
        try {
            List<Integer> managerYear = sawbsMapper.getManagerYear(JwtUtil.getUserForToken());
            List<ManagerYearVo> list = new ArrayList<>();
            for (Integer year : managerYear) {
                SimpleJson managerForUserYear = getManagerForUserYear(new DynamicMessage(year, null, null, JwtUtil.getUserForToken()));
                list.add((ManagerYearVo) managerForUserYear.getData());
            }
            managerAllVo.setYears(list);
        } catch (Exception e) {
            e.printStackTrace();
            return new SimpleJson(1, "无信息");
        }
        return new SimpleJson(managerAllVo);
    }

    @Override
    public SimpleJson applySapStudy(DynamicMessage dynamicMessage) {
        try {
            SapSawbsUser sapSawbsUser = sawbsMapper.getSapSawbsUser(dynamicMessage);
            UserMessage userMessage = userMapper.getUserMessage(JwtUtil.getUserForToken());
            if (userMessage.getQq() == null || Objects.equals(userMessage.getQq(), "无")) {
                return new SimpleJson(1, "加入软件协会学习小组必须绑定QQ，你可以通过修改密码的接口来绑定QQ");
            }
            if (sapSawbsUser != null) {
                if (sapSawbsUser.getSawbsUserSurvive() == 1) {
                    return new SimpleJson(2, "您已退出当前活动，如果想加入只能等待下一次活动或者联系会长");
                } else {
                    return new SimpleJson(1, "你已经加入当前活动，请勿重复提交");
                }
            } else {
                sawbsMapper.applySapStudy(dynamicMessage);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new SimpleJson(1, "申请失败，请联系会长解决");
        }
        return SimpleJson.SUCCESS;
    }

    @Override
    public SimpleJson isJoinSapStudy(DynamicMessage dynamicMessage) {
        SapSawbsUser sapSawbsUser = sawbsMapper.getSapSawbsUser(dynamicMessage);
        if (sapSawbsUser == null) {
            return new SimpleJson(0, "还没有加入软件协会学习小组！");
        } else {
            if (sapSawbsUser.getSawbsUserSurvive() == 0) {
                return new SimpleJson(1, "已经加入软件协会学习小组");
            } else {
                return new SimpleJson(2, "已经退出软件协会学习小组");
            }
        }
    }

    @Override
    public SimpleJson quitSawbs(DynamicMessage dynamicMessage) {
        try {
            sawbsMapper.quitSawbs(dynamicMessage);
        } catch (Exception e) {
            e.printStackTrace();
            return new SimpleJson(2, "退出学习小组失败，请联系会长解决");
        }
        return new SimpleJson(0, "你已经成功退出学习小组");
    }

    @Override
    public SimpleJson submitSawbsForWeek(DynamicMessage dynamicMessage, MultipartFile file) {
        SapSawbsUserResults submitForUserTask = sawbsMapper.isSubmitForUserTask(dynamicMessage);
        if (submitForUserTask.getSawbsUserResultsSubmitted() == 1) {
            return new SimpleJson(1, "请不要重复提交，如果想要修改提交的内容，刷新页面即可");
        }
        try {
            String cosUrl;
            try {
                cosUrl = getSawbsFileUrl(file);
            } catch (IOException e) {
                e.printStackTrace();
                return new SimpleJson(1, "文件上传失败");
            }
            sawbsMapper.submitTaskForWeek(dynamicMessage, new Timestamp(System.currentTimeMillis()), cosUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return new SimpleJson(1, "sql执行出错");
        }
        UserMessage userMessage = userMapper.getUserMessage(JwtUtil.getUserForToken());
        String realName = userMessage.getRealName();
        String qq = userMessage.getQq();
        String managerUsername = submitForUserTask.getSawbsUserResultsManagerUsername();
        String qqByUsername = userMapper.getQQByUsername(managerUsername);
        String managerName = submitForUserTask.getSawbsUserResultsManagerName();
        iMailService.sendHtmlMail(qqByUsername + "@qq.com", "学习小组成员上交学习成功", EmailUntil.sendEmailToManagerForPeopleSubmitTask(managerName, realName, qq, new Timestamp(System.currentTimeMillis()).toString()));
        return new SimpleJson(0, "文件上传成功");
    }

    /**
     * 用户每周提交的.md文件上传到腾讯对象储存然后获取对象储存地址的URL(year，order，week都是为了以周数生成文件名);
     *
     * @param file 文件
     * @return url
     */
    private String getSawbsFileUrl(MultipartFile file) throws IOException {
        String year = dynamicMapper.getYear();
        String order = dynamicMapper.getOrder();
        String week = dynamicMapper.getWeek();
        String cosUrl;
        cosUrl = cosUntil.getCosUrl(file,
                "Sawbs/" + year + "/" + order + "/" + week + "/" +
                        JwtUtil.getUserForToken() +
                        "(" + cacheService.getRealNameCache(cacheService.getRealNameCacheMap(), JwtUtil.getUserForToken()) + ")[" +
                        year + "-" + order + "-" + week + "].md"
        );
        return cosUrl;
    }

    @Override
    public SimpleJson isSubmitForWeek(DynamicMessage dynamicMessage) {
        SapSawbsUserResults submitForUserTask = sawbsMapper.isSubmitForUserTask(dynamicMessage);
        if (submitForUserTask == null) {
            return new SimpleJson(0, "未分配负责人，无法上传！\n分配以后请刷新页面...");
        }
        if (submitForUserTask.getSawbsUserResultsSubmitted() == 0) {
            return new SimpleJson(1, "暂时未提交这周的文件");
        } else {
            return new SimpleJson(2, "已经提交这周的文件");
        }
    }

    /**
     * 修改当前周的任务
     *
     * @param dynamicMessage 动态信息
     * @param file           文件
     * @return ..
     */
    @Override
    public SimpleJson updateSubmitTaskForWeek(DynamicMessage dynamicMessage, MultipartFile file) {
        String sawbsFileUrl;
        try {
            sawbsFileUrl = getSawbsFileUrl(file);
        } catch (IOException e) {
            e.printStackTrace();
            return new SimpleJson(1, "文件上传失败");
        }
        try {
            sawbsMapper.updateSubmitTaskForWeek(dynamicMessage, sawbsFileUrl, new Timestamp(System.currentTimeMillis()));
        } catch (Exception e) {
            e.printStackTrace();
            return new SimpleJson(1, "sql执行出错");
        }
        return new SimpleJson(0, "文件修改成功，如果已经评价，可以联系负责人重新查看后修改评分！");
    }

    @Override
    public SimpleJson getTaskInfoByYearOrderWeek(Integer year, Integer order, Integer week, Integer submit) {
        DynamicMessage message = new DynamicMessage(dynamicMapper.getAllContext());
        List<SapSawbsUserResults> defaultInfo = sawbsMapper.getTaskInfoByYearOrderWeek(message.getYear(), message.getOrder(), message.getWeek(), submit);
        SimpleJson simpleJson = new SimpleJson(
                1,
                "信息不符实际，将默认返回最近一次的周信息;" + message.getYear() + ";" + message.getOrder() + ";" + message.getWeek(),
                defaultInfo);
        if (year == null || (order == null && week != null) || year <= 0 || (order != null && order <= 0) || (week != null && week <= 0)) {
            return simpleJson;
        }
        if (submit != null && submit != 0 && submit != 1) {
            submit = null;
        }
        List<SapSawbsUserResults> info = sawbsMapper.getTaskInfoByYearOrderWeek(year, order, week, submit);
        if (info == null || info.size() == 0) {
            return new SimpleJson(2, "查无信息", null);
        }
        return new SimpleJson(0, "查询成功", info);
    }

    @Override
    public SimpleJson getTaskInfoByUsername() {
        UserMessage userMessage = userMapper.getUserMessage(JwtUtil.getUserForToken());
        if (userMessage.getRole() > 10) {
            return new SimpleJson(1, "权限不足", null);
        }
        List<SapSawbsUserResults> taskInfoByYearOrderWeek = sawbsMapper.getTaskInfoByUsername(
                Integer.valueOf(dynamicMapper.getYear()),
                Integer.valueOf(dynamicMapper.getOrder()),
                Integer.valueOf(dynamicMapper.getWeek()),
                JwtUtil.getUserForToken());
        return new SimpleJson(0, "查询成功", taskInfoByYearOrderWeek);
    }

    @Override
    public void sendReminders() {
        List<SapSawbsUserResults> notSubmitTaskPeople = sawbsMapper.getNotSubmitTaskPeople(Integer.valueOf(dynamicMapper.getYear()), Integer.valueOf(dynamicMapper.getOrder()), Integer.valueOf(dynamicMapper.getWeek()));
        for (SapSawbsUserResults notSubmitTaskPerson : notSubmitTaskPeople) {
            String name = notSubmitTaskPerson.getSawbsUserResultsName();
            String username = notSubmitTaskPerson.getSawbsUserResultsUsername();
            Integer notSubmitTaskMore = sawbsMapper.getNotSubmitTaskMore(username, Integer.valueOf(dynamicMapper.getYear()), Integer.valueOf(dynamicMapper.getOrder()));
            String qq = notSubmitTaskPerson.getSawbsUserResultsQq();
            try{
                iMailService.sendHtmlMail(qq+"@qq.com","本周软件协会学习小组学习成果未上交",EmailUntil.sendEmailToNotSubmitTaskForThisWeek(name,notSubmitTaskMore,new Timestamp(System.currentTimeMillis()).toString()));
            }catch (Exception e){
                log.info(name+":"+qq);
                log.error("没有上交作业的接口发送邮件提示出现错误");
            }
            try {
                Thread.sleep(15000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }
}
